package stackAndQueue;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2022/10/23 14:38
 */
public class Queue {
    static class Node{
        long value;
        Node next;

        Node (long value){
            this.value = value;
            this.next = null;
        }
    }

    // 为了方便头删 + 尾插，记录头节点 + 尾结点
    private Node head;
    private Node last;
    private int size;

    public Queue() {
        this.head = this.last = null;
        this.size = 0;
    }

    public void offer(long e) {
        // 放入队列 -> 尾插
        Node node = new Node(e);
        if (this.last != null) {
            this.last.next = node;
            this.last = node;
        } else {
            this.head = this.last = node;
        }
        this.size++;
    }

    public long poll() {
        if (size == 0) {
            throw new RuntimeException("队列是空的");
        }

        // 记录当前队首元素
        long e = this.head.value;
        // 进行头删
        this.head = this.head.next;
        if (this.head == null) {
            this.last = null;
        }
        size--;

        return e;
    }

    public long peek() {
        if (size == 0) {
            throw new RuntimeException("队列是空的");
        }

        return this.head.value;
    }

    public int size() {
        return this.size;
    }

    public boolean isEmpty() {
        return size() != 0;
    }
    public static void main(String[] args) {
        Queue queue = new Queue();

        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        queue.offer(4);

        System.out.println(queue.peek());   // 1
        queue.offer(5);

        System.out.println(queue.peek());   // 1

        System.out.println(queue.poll());   // 1
        System.out.println(queue.poll());   // 2
        System.out.println(queue.poll());   // 3
        System.out.println(queue.poll());   // 4
        System.out.println(queue.poll());   // 5

        queue.offer(6);
        System.out.println(queue.peek());   // 6
        System.out.println(queue.poll());   // 6
    }
}
